package com.googlecode.spruce.plugins.core.network;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;

import com.googlecode.spruce.core.DefaultPluginResult;
import com.googlecode.spruce.core.ServiceCheckPlugin;
import com.googlecode.spruce.core.ServiceCheckPluginResult;

public class HttpGetRequestServiceCheck implements ServiceCheckPlugin
{
    private String url;

    private int minResponseSize = 0;

    private long maxResponseTime = 0l;

    public ServiceCheckPluginResult execute()
    {
        try
        {
            long responseTime = -System.currentTimeMillis();
            final Content content = Request.Get(this.url).execute().returnContent();
            responseTime += System.currentTimeMillis();

            if (this.maxResponseTime > 0)
            {
                if (responseTime > this.maxResponseTime)
                {
                    return new DefaultPluginResult("Bad HTTP Response Time. Max: " + this.maxResponseTime
                            + " Was: " + responseTime);
                }
            }
            else if (this.minResponseSize > 0)
            {
                final int contentSize = content.asBytes().length;
                if (this.minResponseSize > contentSize)
                {
                    return new DefaultPluginResult("Bad HTTP content size. Min: " + this.minResponseSize
                            + " Was: " + contentSize);
                }
            }

        }
        catch (final ClientProtocolException cpe)
        {
            return new DefaultPluginResult(cpe);
        }
        catch (final IOException ioe)
        {
            return new DefaultPluginResult(ioe);
        }
        catch (final IllegalArgumentException iae)
        {
            return new DefaultPluginResult(iae);
        }

        return new DefaultPluginResult(100);
    }

    public String getUrl()
    {
        return url;
    }

    public void setUrl(final String url)
    {
        this.url = url;
    }

    public int getMinResponseSize()
    {
        return minResponseSize;
    }

    public void setMinResponseSize(final int minResponseSize)
    {
        this.minResponseSize = minResponseSize;
    }

    public long getMaxResponseTime()
    {
        return maxResponseTime;
    }

    public void setMaxResponseTime(final long maxResponseTime)
    {
        this.maxResponseTime = maxResponseTime;
    }
}
